package com.lazyboyl.spring.boot.sharding.sphere.proxy.net.handler.fronted;

import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.proto.MySQLPacket;
import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.proto.mysql.BinaryPacket;
import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.proto.util.ErrorCode;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FrontendCommandHandler extends ChannelHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ChannelHandlerAdapter.class);

    protected FrontendConnection source;

    public FrontendCommandHandler(FrontendConnection source) {
        this.source = source;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        BinaryPacket bin = (BinaryPacket) msg;
        byte type = bin.data[0];
        switch (type) {
            case MySQLPacket.COM_INIT_DB:
                logger.info("---initDB---");
                // just init the frontend
                source.initDB(bin);
                break;
            case MySQLPacket.COM_QUERY:
                logger.info("---query---");
                source.query(bin);
                break;
            case MySQLPacket.COM_PING:
                logger.info("---ping---");
                // todo ping , last access time update
                source.ping();
                break;
            case MySQLPacket.COM_QUIT:
                logger.info("---close---");
                source.close();
                break;
            case MySQLPacket.COM_PROCESS_KILL:
                logger.info("---kill---");
                source.kill(bin.data);
                break;
            case MySQLPacket.COM_STMT_PREPARE:
                // todo prepare支持,参考MyCat
                logger.info("---stmtPrepare---");
                source.stmtPrepare(bin.data);
                break;
            case MySQLPacket.COM_STMT_EXECUTE:
                logger.info("---stmtExecute---");
                source.stmtExecute(bin.data);
                break;
            case MySQLPacket.COM_STMT_CLOSE:
                logger.info("---stmtClose---");
                source.stmtClose(bin.data);
                break;
            case MySQLPacket.COM_HEARTBEAT:
                logger.info("---heartbeat---");
                source.heartbeat(bin.data);
                break;
            default:
                source.writeErrMessage(ErrorCode.ER_UNKNOWN_COM_ERROR, "Unknown command");
                break;
        }
    }
}
